package com.nice.message;

import java.util.List;



import org.apache.log4j.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

public class MessageCodec extends ByteToMessageCodec<Message>{

    private static Logger log = Logger.getLogger(MessageCodec.class);
	@Override
	protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf buf)
			throws Exception {
		ctx.writeAndFlush(msg.toByte());
		log.debug("ecode message success");
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf buf,
			List<Object> out) throws Exception {
		if (buf.readableBytes() < 5)
			return;
		buf.markReaderIndex();
		byte type = buf.readByte();
		int len = buf.readInt();
		if (buf.readableBytes() < len + 8) {
			buf.resetReaderIndex();
			return;
		}
		int from = buf.readInt();
		int to = buf.readInt();
		byte[] body = new byte[len];
		buf.readBytes(body);
		out.add(Message.from(body,type,from,to));
		log.debug("decode message success");
	}
}
